﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class GameManager : ManagerBase<GameManager>
{
    public SelectShipPanel selectShipPanel;
    public Fleet fleet;

    public float timeDifference;

    public LogSystem logSystem;

    private Coroutine timer;

    public float timeScale=1;

    /// <summary>
    /// 每计时一次时
    /// </summary>
    public UnityEvent onTimer;


    private void Start() 
    {
        onTimer.AddListener(OnTimer);
    }

    void Update() 
    {
        Time.timeScale=timeScale;
    }
 
    
    public void StartGame()
    {
        timer=StartCoroutine(Timer());
        OnGameStart();
    }
    

    private void OnGameStart()
    {
        timeDifference = Time.time;
        logSystem.LogLine("<color=#ffffff>舰队出发</color>");
    }

    private void OnTimer()
    {
        FleetMove();
    }

    private void FleetMove()
    {
        float distance=fleet.GetSpeed();
        int angle=Random.Range(0,91);
        if(angle==0)
        {
            fleet.position.x+=distance;
        }else if(angle==90)
        {
            fleet.position.y+=distance;
        }else
        {
            float x=(Mathf.Cos(angle)*distance)+fleet.position.x;
            float y=(Mathf.Sin(angle)*distance)+fleet.position.y;
            fleet.position.x=x.To2F();
            fleet.position.y=y.To2F();  
        }
        //Debug.Log(fleet.position);
        logSystem.LogLine("行驶到"+"<color=#00ff00>"+"(x:"+fleet.position.x+"y:"+fleet.position.y+")"+"</color>");
    }


    public void ShowSelect(GameObject sender)
    {
        OwnsideShipControllerBase controller = sender.GetComponent<OwnsideShipControllerBase>();
        if (controller != null)
        {
            RemoveShip(controller.shipModel.Name);
        }
        selectShipPanel.sender = sender;
        selectShipPanel.gameObject.SetActive(true);
    }

    public void AddShip(string name,OwnsideShipControllerBase controller,ShipTypes type)
    {
        if (fleet == null)
        {
            fleet = new Fleet();
        }
        fleet.AddShip(name, controller, type);
    }

    private void RemoveShip(string name)
    {
        OwnsideShipControllerBase osc=fleet.Remove(name);
        DestroyImmediate(osc);
    }




    /// <summary>
    /// 计时器
    /// </summary>
    /// <returns></returns>
    private IEnumerator Timer()
    {
        while(true)
        {
            yield return new WaitForSeconds(1);
            onTimer.Invoke();
        }
    }

}
